const {
    DESTRUCTION
} = require('dns')
const express = require('express')
const router = express.Router()
//链接menu数据库
const menuModel=require('../../db/menu')

//上传图片中间件
const multer = require('multer')
const path = require('path')
const filePath = './uploads'
const upload = multer({
    storage: multer.diskStorage({
        destination(req, file, cb) {
            cb(null, filePath)
        },
        filename(req, file, cb) {
            //获取后缀
            let suffix = path.extname(file.originalname)
            let filename = +new Date() + Math.floor(Math.random() * 899999) + 100000 + suffix
            cb(null, filename)
        }
    })
})

/* 添加商品：
    方式-post
    路径-/admin/api/menus/add
    请求主体：
       name:String,
       price:Number,
       imgpath:String,
       specifications:String,//规格
       kind:String,//种类
       enable:Boolean//当前是否可点
    响应-成功或失败
*/
//上传文件的局部中间件
router.post('/add', upload.single('imgpath'), (req, res) => {
    //接收数据
    let {
        catname,
        name,
        price,
        spec:specifications,
        kind
    } = req.body
    console.log(req.body)
    /*  name: '玉米肉',
  price: '16',
  spec: [ '大份20个 ￥21.00', '小份15个 ￥16.00' ],
  kind: [ '干饺', '汤饺' ] */
    //获取图片路径
    console.log(req.file)
    /**{
  fieldname: 'imgpath',
  originalname: 'wj.jpeg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './uploads',
  filename: '1678698889378.jpeg',
  path: 'uploads\\1678698889378.jpeg',
  size: 55725
   } */
   //获取上传的图片路径-反斜杠改为斜杠
   let imgpath=req.file.path.replace(/\\/g,'/')
   console.log(imgpath)
   //存入数据库
   menuModel.findOne({name},(err,docs)=>{
    if(err){
        throw new Error(err)
    }
    if(docs){//商品名被占用
        res.json({
            error_code:1,
            msg:'商品已存在'
        })
        return
    }
    menuModel.insertMany({
        name,
        price,
        imgpath,
        catname,
        //数组形式，转成字符串
        specifications:specifications.join('====='),
        kind:kind.join('=====')
    },(err,docs)=>{
        if(err){
            throw new Error(err)
        }
        res.json({
            error_code:0,
            msg:'商品添加成功'
        })
        console.log(docs)
    })
    
   })
})

module.exports = router